package com.ruibang.glass.equipment.service.impl.device;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.equipment.constant.EquipmentErrorCode;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.entity.device.InventoryManagement;
import com.ruibang.glass.equipment.entity.device.OutBoundManagement;
import com.ruibang.glass.equipment.entity.device.SparePartsInventory;
import com.ruibang.glass.equipment.mapper.device.InventoryManagementMapper;
import com.ruibang.glass.equipment.mapper.device.OutBoundManagementMapper;
import com.ruibang.glass.equipment.mapper.device.SparePartsInventoryMapper;
import com.ruibang.glass.equipment.service.OutBoundManagementService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class OutBoundManagementServiceImpl extends ServiceImpl<OutBoundManagementMapper, OutBoundManagement> implements OutBoundManagementService {
    @Autowired
    private InventoryManagementMapper inventoryManagementMapper;
    @Autowired
    private SparePartsInventoryMapper sparePartsInventoryMapper;

    /**
     * 出库列表
     *
     * @param deviceAllPageReq
     * @return
     */
    @Override
    public IPage<OutBoundManagement> queryPage(DeviceAllPageReq deviceAllPageReq) {
        return baseMapper.getCheckList(new Page<>(deviceAllPageReq.getPageNo(), deviceAllPageReq.getPageSize()), deviceAllPageReq);
    }

    /**
     * 新增修改
     *
     * @param repairPlan
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody updateOrAddById(OutBoundManagement repairPlan) {
        if (StringUtils.isNotBlank(repairPlan.getModel()) && StringUtils.isNotBlank(repairPlan.getUnit())
                && StringUtils.isNotBlank(repairPlan.getSparePartsName())
        ) {
            InventoryManagement inventoryManagement = inventoryManagementMapper.selectById(repairPlan.getModel());
            if (inventoryManagement != null) {
                repairPlan.setInventoryId(repairPlan.getSparePartsName());
                repairPlan.setModel(inventoryManagement.getModel());
                repairPlan.setUnit(inventoryManagement.getUnit());
                repairPlan.setSparePartsName(inventoryManagement.getSparePartsName());
            }
        }
        SparePartsInventory sparePartsInventory = sparePartsInventoryMapper.selectOne(Wrappers.<SparePartsInventory>lambdaQuery()
                .eq(SparePartsInventory::getSparePartsName, repairPlan.getSparePartsName()).orderByDesc(SparePartsInventory::getCreateTime).last("limit 1"));
        if (sparePartsInventory == null) {
            throw new ServiceException(EquipmentErrorCode.PARAM_NO_PRODUCT_ERROR.getCode(), EquipmentErrorCode.PARAM_NO_PRODUCT_ERROR.getMsg());
        } else {
            if (sparePartsInventory.getStockQuantity() == null || sparePartsInventory.getStockQuantity() == 0) {
                throw new ServiceException(EquipmentErrorCode.PARAM_NO_PRODUCT_ERROR.getCode(), EquipmentErrorCode.PARAM_NO_PRODUCT_ERROR.getMsg());
            } else {
                Integer count1 = sparePartsInventory.getStockQuantity();
                Integer count2 = repairPlan.getOutboundQuantity();
                if (count1 < count2) {
                    throw new ServiceException(EquipmentErrorCode.LESS_PRODUCT.getCode(), EquipmentErrorCode.LESS_PRODUCT.getMsg());
                } else {
                    Integer quality = sparePartsInventory.getStockQuantity() - repairPlan.getOutboundQuantity();
                    sparePartsInventory.setStockQuantity(quality);
                    sparePartsInventoryMapper.updateById(sparePartsInventory);
                }
            }
        }
        if (StringUtils.isBlank(repairPlan.getId())) {
            baseMapper.insert(repairPlan);
            return ResultBody.success();
        }
        baseMapper.updateById(repairPlan);
        return ResultBody.success();
    }

    /**
     * 导出
     *
     * @param machiningReq
     * @param response
     */

    @Override
    public void export(DeviceAllPageReq machiningReq, HttpServletResponse response) {
        String fileName = "隐患台账" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
        try {
            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            // 设置响应内容类型和字符编码
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");

            // 设置Content-Disposition头部，告诉浏览器这是一个文件下载请求
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 获取导出数据
            IPage<OutBoundManagement> checkList = baseMapper.getCheckList(new Page<OutBoundManagement>(0L, 2000L), machiningReq);
            List<OutBoundManagement> list = checkList.getRecords();

            // 使用EasyExcel写入数据到响应输出流
            EasyExcel.write(response.getOutputStream(), OutBoundManagement.class).excelType(ExcelTypeEnum.XLSX).sheet("隐患台账").doWrite(list);

            // 刷新输出流
            response.flushBuffer();
        } catch (IOException e) {
            throw new ServiceException(EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getCode(), EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getMsg());
        }
    }


}
